<template>
  <view>
    <button @click="handleDownload">下载图片</button>
  </view>
</template>

<script setup>
import { onMounted } from 'vue';
import { getImageNameFromUrl } from '@/utils/common.js'

const handleDownload = async () => {
  try {
    const imageId = 'qiniu://public/wallpaper/images/2025/4/11/1744380127389_49309.webp';
    const imageUrl = `https://cdn.isscloud.site/${imageId.replace('qiniu://', '')}`;


    // #ifdef MP-WEIXIN
    // 微信小程序环境
    const downloadRes = await uni.downloadFile({
      url: imageUrl,
    });

    if (downloadRes.statusCode !== 200) {
      throw new Error('图片下载失败');
    }

    try {
      await uni.saveImageToPhotosAlbum({
        filePath: downloadRes.tempFilePath,
      });
      uni.showToast({
        title: '图片已保存到相册',
        icon: 'none',
      });
    } catch (saveError) {
      if (saveError.errMsg.includes('auth deny')) {
        uni.showModal({
          title: '权限申请',
          content: '需要授权才能保存图片到相册',
          success: (res) => {
            if (res.confirm) {
              uni.openSetting();
            }
          },
        });
      } else {
        uni.showToast({
          title: `保存失败：${saveError.message || saveError.errMsg}`,
          icon: 'none',
          duration: 2000,
        });
      }
    }
    // #endif

    // #ifdef H5
    // H5 环境
	const response = await fetch(imageUrl);
	const blob = await response.blob();
	const url = URL.createObjectURL(blob);
	const a = document.createElement('a');
	a.href = url;
	a.download = Math.floor(Math.random() * 10000) + getImageNameFromUrl(imageUrl);
	document.body.appendChild(a);
	a.click();
	document.body.removeChild(a);
	setTimeout(() => URL.revokeObjectURL(url), 100);
    // #endif
  } catch (error) {
    uni.showToast({
      title: `操作失败：${error.message || error.errMsg}`,
      icon: 'none',
      duration: 2000,
    });
  }
};

onMounted(() => {
  // #ifdef MP-WEIXIN
  // 微信小程序环境下在组件挂载时检查权限
  uni.getSetting({
    success(res) {
      if (!res.authSetting['scope.writePhotosAlbum']) {
        uni.authorize({
          scope: 'scope.writePhotosAlbum',
          success() {
            // 用户已经同意授权
          },
          fail() {
            uni.showModal({
              title: '提示',
              content: '需要您授权保存图片到相册',
              success: function (res) {
                if (res.confirm) {
                  uni.openSetting();
                }
              },
            });
          },
        });
      }
    },
  });
  // #endif
});
</script>    